package com.ruoyi.web.controller.qrcode;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.enums.RetResponse;
import com.ruoyi.common.enums.RetResult;
import com.ruoyi.common.utils.*;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.config.WxConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Description: TODO
 * @Author ONESTAR
 * @Date: 2021/7/16 16:31
 * @Version 1.0
 */
@Controller
@RequestMapping("/qrcode")
@CrossOrigin
public class QrcodeController extends BaseController {

    private static Logger logger = LoggerFactory.getLogger("sys-wx");

    @Autowired
    private IQrcodeService iQrcodeService;

    @Autowired
    private IWxInfoService iWxInfoService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IWxDriverRecordService wxDriverRecordService;

    @Autowired
    private IWxTokenService iWxTokenService;

    @Value("${ruoyi.resourceProfile}")
    private String resourceProfile;

    /**
     * 注册界面 -> 初始化项目机构树
     *
     * @return
     */
    @RequestMapping("/initProgramTrees")
    @ResponseBody
    public RetResult<Object> initProgramTrees() {
        logger.info("initProgramTrees() initProgramTrees:{}");

        try {
            List<Ztree> ztrees = deptService.selectDeptTree(new SysDept());
            return RetResponse.makeOKRsp(ztrees);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("注册界面 -> 初始化项目机构树:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 注册界面 -> 运输车切换项目 -> 回显姓名、手机号
     *
     * @return
     */
    @RequestMapping("/queryWxInfo")
    @ResponseBody
    public RetResult<Object> queryWxInfo(@RequestBody WxInfo wxInfo) {
        logger.info("queryWxInfo() queryWxInfo:{}", wxInfo);

        try {
            List infos = iWxInfoService.selectWxInfoList(wxInfo);
            return RetResponse.makeOKRsp(infos.get(0));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("注册界面 -> 运输车切换项目 -> 回显姓名、手机号:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 注册界面 -> 用户首次注册信息
     *
     * @param wxInfo
     * @return
     */
    @CrossOrigin
    @RequestMapping("/addWxInfo")
    @ResponseBody
    public RetResult<String> addWxInfo(@RequestBody WxInfo wxInfo) {
        logger.info("addWxInfo() addWxInfo:{}", wxInfo);
        try {
            return RetResponse.makeOKRsp(iQrcodeService.insertWxInfo(wxInfo));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("注册界面 -> 用户首次注册信息:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 首页面 -> 判断用户权限 && 扫一扫重定向
     *
     * @param wxInfo
     * @return
     */
    @CrossOrigin
    @RequestMapping("/selectWxInfo")
    @ResponseBody
    public RetResult<Object> selectWxInfo(@RequestBody WxInfo wxInfo) {
        logger.info("selectWxInfo() selectWxInfo:{}", wxInfo);

        try {
            return iQrcodeService.queryUserPerm(wxInfo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("首页面 -> 判断用户权限 && 扫一扫重定向:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 运输车界面 -> 获取次数统计
     *
     * @param driverRecord
     * @return
     */
    @CrossOrigin
    @PostMapping("/queryTrunkNum")
    @ResponseBody
    public RetResult<Object> queryTrunkNum(@RequestBody DriverRecord driverRecord) {
        logger.info("queryTrunkNum() queryTrunkNum:{}", driverRecord);
        try {
            return iQrcodeService.queryTrunkNum(driverRecord);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("运输车界面 -> 获取次数统计:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 运输车界面 -> 生成二维码
     *
     * @param driver
     * @return
     */
    @CrossOrigin
    @PostMapping("/addDriver")
    @ResponseBody
    public RetResult<String> addDriver(@RequestBody Driver driver) {
        logger.info("addDriver() addDriver:{}", driver);

        try {
            return RetResponse.makeOKRsp(iQrcodeService.generateQrcodePath(driver,resourceProfile));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("运输车界面 -> 生成二维码:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 运输车界面 -> 查询运输车最新提交表单信息
     *
     * @param driver
     * @return
     */
    @CrossOrigin
    @PostMapping("/queryDriver")
    @ResponseBody
    public RetResult<Driver> queryDriver(@RequestBody Driver driver) {
        logger.info("queryDriver() queryDriver:{}", driver);

        try {
            return RetResponse.makeOKRsp(iQrcodeService.queryDriverByOpenId(driver).get(0));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("运输车界面 -> 查询运输车最新提交表单信息:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }


    /**
     * 运输车记录界面 -> 查询运输车打卡记录
     *
     * @param wxDriverRecord
     * @return
     */
    @CrossOrigin
    @PostMapping("/queryClockRecord")
    @ResponseBody
    public RetResult<List<WxDriverRecord>> queryClockRecord(@RequestBody WxDriverRecord wxDriverRecord) {
        logger.info("queryClockRecord() queryClockRecord:{}", wxDriverRecord);

        try {
            return RetResponse.makeOKRsp(wxDriverRecordService.selectWxDriverRecordList(wxDriverRecord));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("运输车记录界面 -> 查询运输车打卡记录:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 材料员界面 -> 扫一扫初始化 -> 获取接口授权
     *
     * @param url 扫一扫界面url
     * @return
     */
    @CrossOrigin
    @RequestMapping("/getSign")
    @ResponseBody
    public RetResult<Map<String, String>> getSign(String url) {
        logger.info("getSign() getSign:{}", url);

        try {
            // 获取access_token、ticket
//            WxToken wxToken = iWxTokenService.selectToken();
            String res = HttpClientUtils.get(WxConfig.TOKEN_URL,new HashMap<>());
            String token = JSONObject.parseObject(res).getString("token");
            String ticket = JSONObject.parseObject(res).getString("ticket");

            logger.info("材料员界面 -> 扫一扫初始化 -> 获取token:" + token);
            logger.info("材料员界面 -> 扫一扫初始化 -> 获取ticket:" + ticket);
            return RetResponse.makeOKRsp(JsapiTicketUtil.sign(ticket, url));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("材料员界面 -> 扫一扫初始化 -> 获取接口授权:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 材料员界面 -> 获取次数统计
     *
     * @param driverRecord
     * @return
     */
    @CrossOrigin
    @PostMapping("/queryMaterNum")
    @ResponseBody
    public RetResult<Object> queryMaterNum(@RequestBody DriverRecord driverRecord) {
        logger.info("queryMaterNum() queryMaterNum:{}", driverRecord);
        try {
            return iQrcodeService.queryMaterNum(driverRecord);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("材料员界面 -> 获取次数统计:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 材料员界面 - 切换项目 -> 获取材料员所负责项目列表
     *
     * @param wxMater
     * @return
     */
    @CrossOrigin
    @PostMapping("/queryMaterPerms")
    @ResponseBody
    public RetResult<Object> queryMaterPerms(@RequestBody WxMater wxMater) {
        logger.info("queryMaterPerms() queryMaterPerms:{}", wxMater);
        try {
            return iQrcodeService.queryMaterPerms(wxMater);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("材料员界面 - 切换项目 -> 获取项目列表:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 材料员界面 - 切换项目 - 切换界面 - 保存 -> 获取材料员所负责项目列表
     *
     * @param wxMater
     * @return
     */
    @CrossOrigin
    @PostMapping("/switchDept")
    @ResponseBody
    public RetResult<String> switchDept(@RequestBody WxMater wxMater) {
        logger.info("switchDept() switchDept:{}", wxMater);
        try {
            return iQrcodeService.switchDept(wxMater);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("材料员界面 - 切换项目 -> 获取项目列表:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 材料员界面 -> 查询材料员打卡记录
     *
     * @param wxDriverRecord
     * @return
     */
    @CrossOrigin
    @PostMapping("/queryMaterRecord")
    @ResponseBody
    public RetResult<List<WxDriverRecord>> queryMaterRecord(@RequestBody WxDriverRecord wxDriverRecord) {
        logger.info("queryMaterRecord() queryMaterRecord:{}", wxDriverRecord);

        try {
            return RetResponse.makeOKRsp(wxDriverRecordService.selectWxDriverRecordList(wxDriverRecord));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("材料员界面 -> 查询材料员打卡记录:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 材料员详情界面 -> 材料员查询运输车提交详情信息（包括工作内容、备注）
     *
     * @param driver
     * @return
     */
    @CrossOrigin
    @RequestMapping("/queryDriverDetail")
    @ResponseBody
    public RetResult<Driver> queryDriverDetail(@RequestBody Driver driver) {
        logger.info("queryDriverDetail() queryDriverDetail:{}", driver);

        try {
            return RetResponse.makeOKRsp(iQrcodeService.queryDriverDetailInfo(driver));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("材料员详情界面 -> 材料员查询运输车提交详情信息（包括工作内容、备注）:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 材料员界面 -> 查询当前项目下待审核用户列表
     *
     * @param wxInfo
     * @return
     */
    @CrossOrigin
    @RequestMapping("/queryVerifyUserList")
    @ResponseBody
    public RetResult<List<WxInfo>> queryVerifyUserList(@RequestBody WxInfo wxInfo) {
        logger.info("queryVerifyUserList() queryVerifyUserList:{}", wxInfo);
        wxInfo.setStatus("0");
        try {
            return RetResponse.makeOKRsp(iWxInfoService.selectWxInfoList(wxInfo));
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("材料员详情界面 -> 查询当前项目下待审核用户列表:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 材料员详情界面 -> 审批通过
     *
     * @param driverrecord
     * @return
     */
    @CrossOrigin
    @RequestMapping("/approved")
    @ResponseBody
    public RetResult<String> approved(@RequestBody DriverRecord driverrecord) throws Exception {
        logger.info("approved() approved:{}", driverrecord);

        // 根据项目ID查询对应项目的打卡间隔时间
        SysDept sysDept = deptService.selectDeptById(Long.valueOf(driverrecord.getDeptId()));
        String resut = iQrcodeService.approvedRecord(driverrecord, Long.valueOf(sysDept.getIntervalTime()));
        if (resut.equals("success")) {
            return RetResponse.makeOKRsp("success");
        } else {
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 运输车提交界面 -> 初始化获取供应商列表
     *
     * @return
     */
    @CrossOrigin
    @RequestMapping("/querySupplierList")
    @ResponseBody
    public RetResult<List<String>> querySupplierList(@RequestBody SysDept sysDept) {
        logger.info("querySupplierList() querySupplierList:{}", sysDept);

        try {
            List<Ztree> ztrees = deptService.selectDeptTree(sysDept);
            List<String> suppliers = new ArrayList<>();
            if (StringUtils.isNotEmpty(ztrees)) {
                for (Ztree zt : ztrees) {
                    suppliers.add(zt.getName());
                }
            }
            return RetResponse.makeOKRsp(suppliers);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("运输车提交界面 -> 初始化获取供应商列表:" + e.getMessage());
            return RetResponse.makeErrRsp("fail");
        }
    }

    /**
     * 材料员详情界面 -> 初始化获取工作内容列表
     *
     * @return
     */
    @CrossOrigin
    @RequestMapping("/queryWorkContentList")
    @ResponseBody
    public RetResult<List<String>> queryWorkContentList() throws Exception {
        List<SysDictData> workContentList = sysDictDataService.selectDictDataByType("work_content");
        List<String> workContents = new ArrayList<>();
        if (StringUtils.isNotEmpty(workContentList)) {
            for (SysDictData sysDictData : workContentList) {
                workContents.add(sysDictData.getDictLabel());
            }
            return RetResponse.makeOKRsp(workContents);
        }
        return RetResponse.makeOKRsp(workContents);
    }

    /**
     * 材料员详情界面 -> 初始化根据工作内容获取备注列表
     *
     * @return
     */
    @RequestMapping("/queryRemarks")
    @ResponseBody
    public RetResult<List<String>> queryRemarks(@RequestBody SysDictSon sysDictSon) {
        List<SysDictSon> sons = sysDictDataService.selectDictSonByCode(sysDictSon.getDictCode());
        List<String> remarks = new ArrayList<>();
        if (StringUtils.isNotEmpty(sons)) {
            for (SysDictSon son : sons) {
                remarks.add(son.getLable());
            }
            return RetResponse.makeOKRsp(remarks);
        }
        return RetResponse.makeOKRsp(remarks);
    }

    /**
     * 运输车主界面 -> 核查用户
     *
     * @return
     */
    @RequestMapping("/verify")
    @ResponseBody
    public RetResult<String> verify(@RequestBody WxInfo wxInfo) {
        logger.info("verify() verify:{}", wxInfo);
        try {
            int count = iWxInfoService.updateWxInfo(wxInfo);
            if (count > 0) {
                return RetResponse.makeOKRsp("success");
            } else {
                return RetResponse.makeOKRsp("fail");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("运输车主界面 -> 核查用户:" + e.getMessage());
            return RetResponse.makeOKRsp("fail");
        }
    }




}
